<template>
  <div class="console"  v-loading="loading" >
      <div class="console-tools">
          <div class="console-tools-item">
              <el-button text  @click="saveQueryScript">
                  <el-icon size="16"><Document /></el-icon>
                  保存
              </el-button>
          </div>
         <div class="console-tools-item">
              <el-button  text @click="formatConsoleInput">
                  <el-icon size="16"><MagicStick /></el-icon>
                  美化
              </el-button>
          </div>
      </div>
      <div class="console-option">
          <div class="console-option-item">
              <el-select v-model="params.connectionId" @change="changeConnection" style="width: 220px;">
                  <el-option v-for="item in proxy.$appStore.connectList" :key="item.id" :label="item.name"
                             :value="item.id"/>
              </el-select>
          </div>
          <div class="console-option-item">
              <el-select v-model="params.databaseName" style="width: 220px;">
                  <el-option v-for="item in dataBaseMeta" :key="item.SCHEMA_NAME" :label="item.SCHEMA_NAME"
                             :value="item.SCHEMA_NAME"/>
              </el-select>
          </div>
          <div class="console-option-item">
              <el-button type="primary" plain @click="runConsoleScript">
                  <el-icon size="24" color="#529b2e">
                      <CaretRight/>
                  </el-icon>
                  {{params.runButtonAll?'运行':'运行已选择'}}
              </el-button>
          </div>
          <div class="console-option-item">
              <el-button type="primary" plain @click="runConsoleScript(1)">
                  <Icon icon="ph:tree-structure" width="16"/>
                  解释
              </el-button>
          </div>
      </div>
   <div class="console-edit" :style="showType===1||showType===2?'height: calc(99vh - (99vh * 0.55) - 220px);':'height: calc(99vh - 85px);'">
     <AceEditor  @getEditorInstance="getEditorInstance"/>
   </div>
    <div class="console-data" v-if="showType===1">
        <div class="console-data-tips">
            <div>只读</div>
            <div>查询结果共计{{tableData.length}}条记录</div>
        </div>
        <el-table :data="tableData" border height="calc(99vh * 0.55)" highlight-current-row  @row-click="tableClickRow">
            <el-table-column type="index" width="50" fixed >
                <template #default="scope">
                    <div style="width: 100%;display: flex;justify-content: flex-start;">
                        <div v-if="selectRowIndex===(scope.$index+1)"><el-icon size="18"><CaretRight /></el-icon></div>
                        <div>{{initIndex(scope.$index)}}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column :key="field.COLUMN_NAME" :label="field.COLUMN_NAME"
                             :min-width="getColumnWidth(field.COLUMN_NAME)" :prop="field.COLUMN_NAME" show-overflow-tooltip
                             v-for="field in fieldData">
                <template #default="scope">
                    {{getDateFormat(field,scope.row[field.COLUMN_NAME])}}
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="console-data" v-if="showType===2">

    </div>
  </div>
</template>

<script setup name="MysqlQueryConsole">
import AceEditor from '@/components/aceEditor'
import {formatDate,formatTime} from "@/utils/dateUtils";
import {format} from 'sql-formatter';
const {proxy} = getCurrentInstance();
const consoleData=reactive({
  params:{
    connectionId:null,
    databaseName:null,
    runButtonAll:true,
  },
  dataBaseMeta:[],
  sqlScript:null,
  showType:0,
  fieldData:[],
  tableData:[],
  tableCount: 0,
  loading:false,
  selectRowIndex:0,
  aceEditorInstance:null,
  formData:null,
})

const {params,dataBaseMeta,sqlScript,showType,fieldData,tableData,tableCount,loading,selectRowIndex,aceEditorInstance,formData} =toRefs(consoleData)

function changeConnection(){
  let connect=proxy.$appStore.connectList.find(row=>row.id===params.value.connectionId)
  proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.showDataBase, connect).then(res=>{
    dataBaseMeta.value=res.data.dataList
  })
}

function getEditorInstance(aceEditor) {
    aceEditorInstance.value = aceEditor
    if (formData.value&&formData.value.id) {
        aceEditorInstance.value.session.setValue(formData.value.value)
    }
    aceEditorInstance.value.session.on('change', function (e) {
        sqlScript.value = aceEditorInstance.value.session.getValue();
        params.value.runButtonAll = true
    })
    aceEditorInstance.value.session.selection.on('changeSelection', function (e) {
        let selectionText = aceEditorInstance.value.session.getTextRange(aceEditorInstance.value.getSelectionRange());
        if (selectionText.trim().length > 0) {
            sqlScript.value = selectionText
            params.value.runButtonAll = false
        } else {
            params.value.runButtonAll = true
            sqlScript.value = aceEditorInstance.value.session.getValue();
        }
    })

    aceEditorInstance.value.session.selection.on('changeCursor', function (e) {
        params.value.runButtonAll = true
        sqlScript.value = aceEditorInstance.value.session.getValue();
    })
}

function tableClickRow(row,column,event){
    selectRowIndex.value=(tableData.value.indexOf(row)+1)
}

function initParams() {
  let query= proxy.$route.query;
  if(Object.keys(query).length>0){
    params.value.connectionId=(query.connectId*1)
    changeConnection()
    params.value.databaseName=query.databaseName
      if(query.id){
          formData.value={}
          formData.value.id=query.id*1
          formData.value.label=query.label
          formData.value.value=query.value
          formData.value.createTime=query.createTime
      }
  }
}

function runConsoleScript(isExplain){
    tableCount.value=0
    loading.value = true
  let connect=proxy.$appStore.connectList.find(row=>row.id===params.value.connectionId)
  if(!connect){
    proxy.$modal.msgWarning("请选择一个数据库连接");
    return
  }
  selectRowIndex.value=0
  let localParams={}
  if(isExplain===1){
      localParams.runScript="EXPLAIN   "+sqlScript.value
  }else {
      localParams.runScript=sqlScript.value
  }

  connect.database=params.value.databaseName
  proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole, connect,localParams).then(res=>{
    if(res.code===200){
      if(Array.isArray(res.data.dataList)){
        showType.value=1//列表
        tableData.value=res.data.dataList
        fieldData.value=res.data.fieldList
      }else {
        showType.value=2//结果
      }
    }else {
      proxy.$modal.alertError(res.message)
      loading.value = false
    }
  })
}

function formatConsoleInput() {
    aceEditorInstance.value.session.setValue(format(aceEditorInstance.value.session.getValue(), {language: 'mysql'}))
}


function getDateFormat(field,fieldValue){
    if(field.DATA_TYPE==='datetime'||field.DATA_TYPE==='timestamp'){
        return formatTime(fieldValue);
    }
    if(field.DATA_TYPE==='date'){
        return formatDate(fieldValue);
    }
    return fieldValue;
}

function initIndex(index) {
    let rowIndex = index + 1
    if(tableCount.value===0){
        loading.value = false
    }else if(rowIndex===tableCount.value){
        loading.value = false
    }
    return rowIndex;
}

function getColumnWidth(columnText) {
    if (columnText.length > 20) {
        return 180;
    }
    if (columnText.length > 10) {
        return 160;
    }
    if (columnText.length > 5) {
        return 120;
    }
    return 80;
}

function saveQueryScript() {
  let connect = proxy.$appStore.connectList.find(row => row.id === params.value.connectionId)
  if (!connect) {
    proxy.$modal.msgWarning("请选择一个数据库连接");
    return
  }
  if (!params.value.databaseName) {
    proxy.$modal.msgWarning("请选择一个数据库");
    return;
  }
  connect.database = params.value.databaseName
  let script = aceEditorInstance.value.session.getValue()
  if (formData.value && formData.value.id) {
    formData.value.value = script
    formData.value.createTime = formatTime(new Date())
    proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.saveQueryScript, connect, formData.value).then(res => {
      formData.value.id = res.data
      proxy.$modal.msgSuccess("操作成功！");
    })
  } else {
    formData.value = {}
    proxy.$prompt('请输入脚本名称', {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /\S/,
      inputErrorMessage: "脚本名称不能为空",
    }).then(({value}) => {
      formData.value.label = value
      formData.value.value = script
      formData.value.createTime = formatTime(new Date())
      proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.saveQueryScript, connect, formData.value).then(res => {
        formData.value.id = res.data
        proxy.$modal.msgSuccess("操作成功！");
      })
    }).catch(() => {
    });
  }
}

const handleEvent = async (event) => {
  if (event.keyCode === 83) {
    if (event.ctrlKey && event.code === 'KeyS') {
      event.preventDefault()
      event.returnValue = false;
      saveQueryScript()
    }
  }
}

onMounted(() => {
  window.addEventListener('keydown', handleEvent)
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleEvent)
});
initParams()
</script>
<style  lang="scss">
.console{
  width: 100%;
  height: 99vh;
  user-select: text;
  &-option{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    &-item{
        margin: 3px 10px 2px 2px;
    }
  }
  &-tools{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    border-bottom: 1px solid #DCDFE6;
    margin-left: 3px;
    &-item{
      border-left:  1px solid #DCDFE6
    }
  }
  &-edit{
    width: 100%;
  }
  &-data{
    width: 100%;
    &-tips{
        height: 24px;
        line-height: 24px;
        display: flex;
        justify-content: flex-start;
        font-size: 12px;
        div {
            padding: 0 10px;
            border-left: 1px solid #DCDFE6;
            border-top: 1px solid #DCDFE6;
        }
    }
  }

}

:deep(.el-table) {
    --el-table-row-hover-bg-color: transparent;
    --el-table-header-bg-color: transparent;
    --el-table-header-text-color: #303133;
}

:deep(.el-table thead th) {
    font-weight: normal;
}

</style>
